const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const User = require('../models/userModel');
const Joi = require('joi');

// 登录
const login = async (req, res) => {
    const { username, password } = req.body;
    const user = await User.getUserByUsername(username);

    if (!user) return res.status(400).json({ error: '用户不存在' });

    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) return res.status(401).json({ error: '密码错误' });

    await User.updateRecentLogin(user.id); // 更新最近登录时间

    const payload = {
        id: user.id,
        username: user.username,
        role: user.role
    };

    const token = jwt.sign(payload, process.env.JWT_SECRET || 'default_secret', {
        expiresIn: process.env.JWT_EXPIRES_IN || '72h'
    });

    res.json({ token });
};

// 注册
const register = async (req, res) => {
    const schema = Joi.object({
        username: Joi.string().min(3).required(),
        phone: Joi.string().pattern(/^[0-9]{11}$/).required(),
        password: Joi.string().min(6).required(),
        role: Joi.number().valid(1, 2).default(2), // 1=admin,2=user
        id_number: Joi.string().length(18).allow(null, ''),
        bank_account: Joi.string().allow(null, ''),
        bank_number: Joi.string().allow(null, ''),
        avatar: Joi.string().uri().allow(null, ''),
        laborTeam: Joi.number().allow(null),
        status: Joi.number().default(1)
    });

    const { error } = schema.validate(req.body);
    if (error) return res.status(400).json({ error: error.details[0].message });

    const { username, phone, password, role, id_number, bank_account, bank_number, avatar, laborTeam, status } = req.body;

    const existingUser = await User.getUserByUsername(username);
    if (existingUser) return res.status(409).json({ error: '用户名已存在' });

    const existingPhone = await User.getUserByPhone(phone);
    if (existingPhone) return res.status(409).json({ error: '手机号已注册' });

    const hashedPassword = await bcrypt.hash(password, 10);

    const userId = await User.createUser({
        username,
        phone,
        password: hashedPassword,
        role,
        id_number,
        bank_account,
        bank_number,
        avatar,
        laborTeam,
        status
    });

    res.status(201).json({ message: '注册成功', userId });
};

// 查询所有用户
const getAllUsers = async (req, res) => {
    const users = await User.getAllUsers();
    res.json(users);
};

// 修改用户
const updateUser = async (req, res) => {
    const { id } = req.params;
    const updates = req.body;

    const existingUser = await User.getUserByUsername(updates.username);
    if (existingUser) return res.status(409).json({ error: '用户名已存在' });
    const existingPhone = await User.getUserByPhone(updates.phone);
    if (existingPhone) return res.status(409).json({ error: '手机号已注册' });

    const success = await User.updateUser(id, updates);

    if (!success) return res.status(404).json({ error: '用户不存在或更新失败' });
    res.json({ message: '更新成功' });
};

// 删除用户（软删除）
const deleteUser = async (req, res) => {
    const { id } = req.params;
    const success = await User.deleteUser(id);

    if (!success) {
        return res.status(404).json({ error: '用户不存在或已删除' });
    }

    res.json({ message: '用户已标记为删除' });
};

module.exports = {
    login,
    register,
    getAllUsers,
    updateUser,
    deleteUser
};
